package com.declum.archon.chunkserver.handler.request;

import java.util.HashMap;

/**
 * Class holds the information that will be sent when the client is requesting
 * for creating chunk.
 * 
 * @author Clement
 * 
 */
public class CreateChunkInfo {
	/**
	 * Stores whether the header received from client is Acknowledged
	 */
	boolean					acknowledged	= false;
	/**
	 * Stores the received header
	 */
	String					receivedHeader	= "";
	boolean					headerRecieved	= false;

	/**
	 * Key/Value pair data structure for headers
	 */
	HashMap<String, String>	headers			= new HashMap<String, String>();

	/**
	 * Used to check whether the required header is received or not
	 * 
	 * @return
	 */
	public boolean isHeaderRecieved() {
		return this.headerRecieved;
	}

	/**
	 * Used to check whether the acknowledgment is sent
	 * 
	 * @return
	 */
	public boolean isAcknowledged() {
		return this.acknowledged;
	}

	/**
	 * Set the acknowledgment status
	 * 
	 * @param acknowledged
	 *            true/false
	 */
	public void setAcknowledged(boolean acknowledged) {
		this.acknowledged = acknowledged;
	}

	/**
	 * Appends the given string to header and once all are received, it will
	 * parse the String.
	 * 
	 * @param recievedData
	 *            data to be appended
	 * @throws Exception
	 *             if any exception during the parsing
	 */
	public void appendHeaderString(byte[] recievedData) throws Exception {
		this.receivedHeader += new String(recievedData);
		if (this.receivedHeader.endsWith("\r\n\r\n")) {
			this.headerRecieved = true;
			this.parseHeader();
		}
	}

	/**
	 * Returns the value associated with the given header
	 * 
	 * @param header
	 *            key for which the value is needed
	 * @return value of the header
	 */
	public String getHeader(String header) {
		return this.headers.get(header);
	}

	/**
	 * Parser the header based on the HTTP Header protocol. Each line will be
	 * take and key/value pair will be taken
	 * 
	 * @throws Exception
	 */
	public void parseHeader() throws Exception {
		for (String line : this.receivedHeader.split("\r\n")) {
			this.parseLine(line);
		}
	}

	/**
	 * It parses the line based on the ":"
	 * 
	 * @param data
	 * @throws Exception
	 */
	private void parseLine(String data) throws Exception {
		int indexOf = data.indexOf(':');
		if (indexOf == -1) {
			throw new Exception("Not a proper line '" + data + "'");
		}
		String header = data.substring(0, indexOf).trim();
		String value = data.substring(indexOf + 1, data.length()).trim();
		this.headers.put(header, value);
	}

	/**
	 * Gives all the received headers
	 * 
	 * @return
	 */
	public String getHeaders() {
		return this.receivedHeader;
	}

}
